﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Microsoft.Extensions.Caching.Memory;
using NationalD3.Domain.Base;
using NationalD3.Domain.Commands.Students;
using NationalD3.Domain.Entities;
using NationalD3.Domain.Events;
using NationalD3.Domain.Interfaces;
using NationalD3.Domain.Notifications;
using NationalD3.Domain.ValueObjects;

namespace NationalD3.Domain.CommandHandlers
{
    public class StudentCommandHandler : CommandHandler,
                            IRequestHandler<RegisterStudentCommand, Unit>,
                            IRequestHandler<UpdateStudentCommand, Unit>,
                            IRequestHandler<DeleteStudentCommand, Unit>

    {

        private readonly IStudentRepository _studentRepository;

        private readonly IUnitOfWork _uow;
        // 注入中介处理接口
        private readonly IEventBus _bus;

        public StudentCommandHandler(IStudentRepository studentRepository,
                                    IUnitOfWork uow, 
                                    IEventBus bus)
            :base(uow, bus)
        {
            _studentRepository = studentRepository;
            _bus=bus;
        }

        /// <summary>
        /// 添加学生命令的处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<Unit> Handle(RegisterStudentCommand request, CancellationToken cancellationToken)
        {
            //1. 对命令对象进行验证
            if (!request.IsValid())
            {
                NotifyValidationErrors(request);
                return Task.FromResult(new Unit());
            }

            //检查是否邮件重复
            if (_studentRepository.GetByEmail(request.Email) != null)
            {
                //发送领域通知
                _bus.RaiseEvent(new DomainNotification("Email", "该邮箱已经被使用！"));

                return Task.FromResult(new Unit());
            }

            //2.实例化领域模型对象
            Address address = new Address(request.Province, request.City, request.County, request.Street);
            var student = new Student(Guid.NewGuid(), request.Name, request.Email, request.Phone, request.BirthDate, address);


            //3. 持久化（把学生添加到数据库中）
            _studentRepository.Add(student);

            if (Commit())
            {
                //4.提交成功，触发领域事件（对此事件感兴趣的，可以进一步业务操作：比如发送邮件，这种处理是异步的）
                _bus.RaiseEvent(new StudentRegisteredEvent(student.Id,student.Name,student.Email,student.BirthDate,student.Phone));
            }

            return Task.FromResult(new Unit());

        }

        public Task<Unit> Handle(UpdateStudentCommand request, CancellationToken cancellationToken)
        {
                if (!request.IsValid())
                {
                    NotifyValidationErrors(request);
                    return Task.FromResult(new Unit());
                }
                //2.实例化领域模型对象
                Address address = new Address(request.Province, request.City, request.County, request.Street);
                var student = new Student(request.Id, request.Name, request.Email, request.Phone, request.BirthDate, address);
                _studentRepository.Update(student);
                if (Commit())
                {
                    //4.提交成功，触发领域事件（对此事件感兴趣的，可以进一步业务操作：比如发送邮件，这种处理是异步的）
                    _bus.RaiseEvent(new StudentRegisteredEvent(student.Id, student.Name, student.Email, student.BirthDate, student.Phone));
                }

                return Task.FromResult(new Unit());
            
          
        }

        public Task<Unit> Handle(DeleteStudentCommand request, CancellationToken cancellationToken)
        {
            throw new NotImplementedException();
        }
    }
}
